package flickr.managers
{
	import flash.events.EventDispatcher;
	
	import flickr.events.PhotosGetInfoEvent;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	import mx.utils.StringUtil;
	
	public class FlickrManager extends EventDispatcher
	{
		private const APIKEY:String = "19063319fca0797de428f2c15e717590";
		private const SECRET:String = "760a3193ae47fce6";
		private const FLICKR_API_FORMATSTR:String = "http://api.flickr.com/services/rest/?method={0}&api_key={1}&{2}";
		
		private const API_PHOTOS_GET_INFO:String = "flickr.photos.getInfo";
		
		private var service:HTTPService;
		
		public function FlickrManager()
		{
			service = new HTTPService();
			service.method = "GET";
			service.showBusyCursor = true;
			
			service.addEventListener(ResultEvent.RESULT, OnResult);
			service.addEventListener(FaultEvent.FAULT, OnFault);
		}
		
		private var token_photoGetInfo:AsyncToken;
		private var getPhotoReceiver:EventDispatcher;
		public function getPhoto(target:EventDispatcher, photoid:String, username:String):void
		{
			getPhotoReceiver = target;
			
			var params:String = "photo_id=" + photoid;
			service.url = StringUtil.substitute(FLICKR_API_FORMATSTR, API_PHOTOS_GET_INFO, APIKEY, params);
			token_photoGetInfo = service.send();
		}
		
		private function OnResult(event:ResultEvent):void
		{
			switch ( event.token )
			{
				case token_photoGetInfo:
				{
					if ( event.result.rsp.stat == "ok" )
					{
						var farmid:Number = event.result.rsp.photo.farm;
						var serverid:String = event.result.rsp.photo.server;
						var id:String = event.result.rsp.photo.id;
						var secret:String = event.result.rsp.photo.secret;
						// http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg
						var photourl:String = StringUtil.substitute("http://farm{0}.static.flickr.com/{1}/{2}_{3}.jpg", farmid, serverid, id, secret);
						var evt:PhotosGetInfoEvent = new PhotosGetInfoEvent(PhotosGetInfoEvent.RESULT);
						evt.photourl = photourl;
						getPhotoReceiver.dispatchEvent(evt);
					}
					else
					{
						
					}
					break;
				}
				default:
					break;
			}
		}
		private function OnFault(event:FaultEvent):void
		{
			trace(event.fault);
		}
	}
}